import {quillEditor} from 'vue-quill-editor'
import Quill from 'quill'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

// 工具栏配置
const toolbarOptions = [
    ['bold', 'italic', 'underline'],
    ['blockquote', 'code-block'],
    [{'header': 1}, {'header': 2}],
    [{'list': 'ordered'}, {'list': 'bullet'}],
    [{'indent': '-1'}, {'indent': '+1'}],
    [{'size': ['small', false, 'large', 'huge']}],
    [{'color': []}, {'background': []}],
    [{'font': []}],
    ['image'],
];

export default {
    components: {
        quillEditor
    },
    data() {
        return {
            title: '',
            classify_id: '',
            class_list: [],
            type:1,
            store_id:0,
            ruleForm: {
                title: '',
                postData: {},
                code:'',
                min_price: '',
                status: 1,
                radio:"1",
                value: '',
                synchronous:'1'
            },
            class_list: [{  //类型
                value: '图文',
                label: '图文'
            },{
                value: '系列',
                label: '系列'
            }],
            rules: {
                name: [
                    { required: true, message: '请输入图片名称', trigger: 'blur' },
                ],
            },
            tableData:[{
                label_number: '2016-05-02',
                name: '王小虎',
                address: '上海市普陀区金沙江路 1518 弄'
            }],
            imgList:[],				//图片列表
            postData: {},			//七牛云postData
            descImageUrl:'',		//图片
            desc_img:false,			//是否展示删除
            domain:'',				//图片域名

            // 富文本编辑器配置
            header: {token: sessionStorage.token},              //有的图片服务器要求请求头需要有token之类的参数，写在这里
            editorOption: {
                placeholder: '',
                theme: 'snow',                                  //样式
                modules: {
                    toolbar: {
                        container: toolbarOptions,              //工具栏
                        handlers: {
                            'image': function (value) {
                                if (value) {
                                    document.querySelector('.avatar-uploader input').click()
                                } else {
                                    this.quill.format('image', false);
                                }
                            }
                        }
                    }
                }
            },
            uploadData:{},
            value2: false, //状态开关
            radio:"1",
            input1:""
        }
    },

    //进入页面加载
    mounted: function() {
        var that = this;
        //在缓存中获取值
        that.user_name = sessionStorage.getItem("user_name");
        that.user_id = sessionStorage.getItem("user_id");
        that.token = sessionStorage.getItem("access-token");
        if((!that.token) || (!that.user_id) || (!that.user_name)) {
            that.$router.push('/login');
        }

        //获取七牛云token
        that.getQiNiuToken();

        // 获取分类列表
        that.get_classify();
    },

    //方法
    methods: {
        //请求api
        submitForm(formName) {
            var that = this;
            this.$refs[formName].validate((valid) => {
                if(valid) {
                    if(that.swiper_id === 0) {
                        that.addCitySwiper();
                    } else {
                        that.editCitySwiper();
                    }
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },

        //获取七牛云token
        getQiNiuToken: function() {
            var that = this;
            //请求登陆接口
            that.$http.post(that.adminApi.api_url + "/Qiniu/getToken", {
                token: that.token,
            }, {
                emulateJSON: true
            }).then(
                function(res) {
                    // 处理成功的结果
                    that.postData = {
                        token: res.body.upToken,
                    }
                    that.domain=res.body.domain;
                },
                function() {
                    // 处理失败的结果
                    that.$message({
                        type: 'error',
                        message: `操作提示: ${ '处理异常' }`
                    });
                });
        },

        //上传图片
        //删除
        descRemove(file, fileList) {
            var that = this;
            that.imgList = fileList;
        },
        descPictureCardPreview(file) {
            this.descImageUrl = file.url;
            this.desc_img = true;
        },
        descError(res) { //显示错误
            console.log(res)
        },
        descAvatarSuccess(res, file) { //上传成功后在图片框显示图片
            var that = this;
            var imageUrl = {
                url: that.domain + res.key,
                uid:file['raw']['uid']
            };
            that.imgList.push(imageUrl);
        },
        //文件超出个数限制时的钩子
        descExceed(files, fileList) {
            this.$message.error('只能上传一张图片');
        },

        //添加
        addCitySwiper:function () {
            var that = this;

            if(that.imgList.length === 0){
                that.$message({
                    type: 'error',
                    message: `操作提示: ${ '请上传图片' }`
                });
                return false;
            }
            //请求的数据
            var formData = {};
            formData.token = that.token;
            formData.type = that.type;
            if(that.type === 1) {
                formData.pid = that.city_id;
            }else {
                formData.pid = that.store_id;
            }
            formData.title = that.ruleForm.name;
            formData.picture = that.imgList[0]['url'];
            formData.url = that.ruleForm.url;
            formData.sort = that.ruleForm.sort;
            formData.status = that.ruleForm.radio;


            //请求邀请者列表
            that.$http.post(that.adminApi.api_url + "/Bannerimg/add", formData, {
                emulateJSON: true
            }).then(
                function(res) {
                    // 处理成功的结果
                    that.$message({
                        type: 'success',
                        message: `操作提示: ${ '添加成功' }`
                    });
                    that.$router.push({path:'/commodity/c_swiper_list',query:{city_id:that.city_id,type:that.type,store_id:that.store_id}});
                },
                function() {
                    // 处理失败的结果
                    that.$message({
                        type: 'error',
                        message: `操作提示: ${ '处理异常' }`
                    });
                });
        },

        //轮播详情
        detail:function () {
            var that = this;
            //请求的数据
            var formData = {};
            formData.token = that.token;
            formData.id = that.swiper_id;

            //请求邀请者列表
            that.$http.post(that.adminApi.api_url + "/Bannerimg/show_edit", formData, {
                emulateJSON: true
            }).then(
                function(res) {
                    that.ruleForm.name=res.body.title;
                    that.ruleForm.sort=res.body.sort;
                    that.ruleForm.url=res.body.url;
                    that.ruleForm.radio=res.body.status.toString();
                    that.imgList.push({
                        url: res.body.picture
                    })
                },
                function() {
                    // 处理失败的结果
                    that.$message({
                        type: 'error',
                        message: `操作提示: ${ '处理异常' }`
                    });
                });
        },

        //修改
        editCitySwiper:function () {
            var that = this;
            if(that.imgList.length === 0){
                that.$message({
                    type: 'error',
                    message: `操作提示: ${ '请上传图片' }`
                });
                return false;
            }

            //请求的数据
            var formData = {};
            formData.token = that.token;
            formData.type = that.type;
            formData.id = that.swiper_id;
            if(that.type === 1) {
                formData.pid = that.city_id;
            }else {
                formData.pid = that.store_id;
            }
            formData.title = that.ruleForm.name;
            formData.picture = that.imgList[0]['url'];
            formData.url = that.ruleForm.url;
            formData.sort = that.ruleForm.sort;
            formData.status = that.ruleForm.radio;

            //请求API
            that.$http.post(that.adminApi.api_url + "/Bannerimg/edit", formData, {
                emulateJSON: true
            }).then(
                function(res) {
                    // 处理成功的结果
                    that.$message({
                        type: 'success',
                        message: `操作提示: ${ '修改成功' }`
                    });
                    that.$router.push({path:'/commodity/c_swiper_list',query:{city_id:that.city_id,type:that.type,store_id:that.store_id}});
                },
                function() {
                    // 处理失败的结果
                    that.$message({
                        type: 'error',
                        message: `操作提示: ${ '处理异常' }`
                    });
                });
        },

        //返回
        cancel:function () {
            var that = this;
            that.$router.push({path:'/commodity/manage',query:{city_id:that.city_id,type:that.type,store_id:that.store_id}});
        },

        /**
         * 获取商品分类列表
         * jihaichuan
         */
        get_classify: function () {
            let that = this;
            let formData = {};
            formData.token = that.token;
            that.$http.post(that.adminApi.api_url + "/category/index", formData, {
                emulateJSON: true
            }).then(function(res) {
                let body = res.body;
                if (body.count > 0){
                    for (let i in body.list) {
                        that.class_list.push({
                            id: body.list[i].id,
                            name: body.list[i].name
                        });
                    }
                }
                console.log(that.class_list);
            });
        }
    }
}